package com.example.stlink.fragments;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.stlink.BuildConfig;
import com.example.stlink.R;
import com.example.stlink.activitys.fragmentChild.activityUserInfo.UserInfoAbout;
import com.example.stlink.activitys.fragmentChild.activityUserInfo.UserInfoDetail;
import com.example.stlink.activitys.fragmentChild.activityUserInfo.UserInfoRecord;
import com.example.stlink.activitys.fragmentChild.activityUserInfo.UserInfoSetting;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.utils.MySQLiteDAO;

import java.io.File;
import java.util.List;

public class UserInfoFragment extends Fragment {

    private static Button btSetting;
    private static Button btAbout;
    private static Button btShare;
    private static Button btRecord;
    private static ConstraintLayout clBaseInfo;

    private static ImageView ivHeadImg;
    private static TextView tvUserName;
    private static TextView tvSchool;

    private static AppCompatActivity mAppCompatActivity;

    private static ActivityResultLauncher<Intent> intentActivityResultLauncher;

    private static Handler shareHandler;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_my_info, container, false);

        initView(view);
        return view;
    }

    /**
     * 获取UserInfoFragment实例
     * @param str 说明，，占位
     * @return 返回UserInfoFragment实例
     */
    public static UserInfoFragment newInstance(String str, AppCompatActivity appCompatActivity){
        UserInfoFragment frag = new UserInfoFragment();
        mAppCompatActivity = appCompatActivity;
        intentActivityResultLauncher = mAppCompatActivity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            System.out.println("registerForActivityResult...........................");
            if (resultCode == Activity.RESULT_OK) {
                assert data != null;
                mAppCompatActivity.getIntent().putExtras(data.getExtras());
                refreshData();
            }
        });

        return frag;
    }

    public static void initView(View view){
        btSetting = view.findViewById(R.id.bt_setting);
        btAbout = view.findViewById(R.id.bt_about);
        btShare = view.findViewById(R.id.bt_share);
        btRecord = view.findViewById(R.id.bt_record);
        clBaseInfo = view.findViewById(R.id.base_info);
        ivHeadImg = view.findViewById(R.id.iv_head_img);
        tvUserName = view.findViewById(R.id.tv_user_name);
        tvSchool = view.findViewById(R.id.tv_school);

        MySQLiteDAO mySQLiteDAO = MySQLiteDAO.newInstance();

        refreshData();

        initOnClickListener();
    }

    public static void refreshData(){

        Bundle bundle = mAppCompatActivity.getIntent().getExtras();
        Integer roleId = (Integer) bundle.get(ModelFieldConstants.ROLE_ID);
        String userName = (String) bundle.get(ModelFieldConstants.USER_NAME);
        String avatar = (String) bundle.get(ModelFieldConstants.AVATAR);
        String schoolName = (String) bundle.get(ModelFieldConstants.COLLEGE_NAME);

        if(roleId == 0){
            ivHeadImg.setImageResource(R.mipmap.student);
        }
        if(avatar != null){
            Glide.with(mAppCompatActivity)
                    .load(avatar)
                    //添加圆角
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
                    .into(ivHeadImg);
        }
        if(userName != null){
            tvUserName.setText(userName);
        }
        if(schoolName != null){
            tvSchool.setText(schoolName);
        }

    }

    public static void initOnClickListener(){

        btSetting.setOnClickListener(v -> {
            Intent intent = new Intent(mAppCompatActivity, UserInfoSetting.class);
            intent.putExtras(mAppCompatActivity.getIntent().getExtras());
            intentActivityResultLauncher.launch(intent);
        });
        //关于
        btAbout.setOnClickListener(v -> {
            Intent intent = new Intent(mAppCompatActivity, UserInfoAbout.class);
            intent.putExtras(mAppCompatActivity.getIntent().getExtras());
            intentActivityResultLauncher.launch(intent);
        });
        //分享
        btShare.setOnClickListener(v -> {
            shareHandler = new Handler(msg -> {
                if(msg.arg1 == 1){
                    Intent shareIntent = (Intent) msg.obj;
                    intentActivityResultLauncher.launch(Intent.createChooser(shareIntent, "分享apk"));
                }
                return false;
            });
            shareApk();
        });
        btRecord.setOnClickListener(v -> {
            Intent intent = new Intent(mAppCompatActivity, UserInfoRecord.class);
            intent.putExtras(mAppCompatActivity.getIntent().getExtras());
            intentActivityResultLauncher.launch(intent);
        });
        clBaseInfo.setOnClickListener(v -> {
            Intent intent = new Intent(mAppCompatActivity, UserInfoDetail.class);
            intent.putExtras(mAppCompatActivity.getIntent().getExtras());
            intentActivityResultLauncher.launch(intent);
        });
    }

    private static void shareApk(){
        new Thread(() -> {
            PackageManager mPackageManager = mAppCompatActivity.getPackageManager();
            List<PackageInfo> packageInfoList = mPackageManager.getInstalledPackages(0);
            System.out.println("UserInfoFragment:PackageInfo : " + packageInfoList);
            try {
                ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo("com.example.stlink", 0);
                File apkFile = new File(applicationInfo.sourceDir);

                Intent shareIntent = new Intent();
                // 设置该意图对象作为活动发送
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("*/*");
                // 给目标应用一个临时的读授权，如果要写权限，则是FLAG_GRANT_WRITE_URI_PERMISSION
                shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                // 第二个参数就是AndroidManifest中配置的authorities，即包名.fileProvider
                Uri contentUri = FileProvider.getUriForFile(mAppCompatActivity, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
                shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);

                Message message = new Message();
                message.arg1 = 1;
                message.obj = shareIntent;
                shareHandler.sendMessage(message);

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
